package com.powergisol.gis.service.impl;

import cn.hutool.core.util.StrUtil;
import com.powergisol.gis.dao.TabDataMenuMapper;
import com.powergisol.gis.dao.TabUserMapper;
import com.powergisol.gis.entity.TabUser;
import com.powergisol.gis.service.TabUserService;
import com.powergisol.gis.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TabUserServiceImpl implements TabUserService {

    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    @Autowired
    private TabUserMapper userMapper;
    @Autowired
    private TabDataMenuMapper menuMapper;

    @Override
    public Result synUser(List<TabUser> users) {
        Result result = new Result();
        StringBuffer buffer = new StringBuffer();
        for (TabUser user:users) {
            int num = userMapper.countUserByUserName(user.getUserName());
            if(num == 0){
                user.setStatus(1);
                user.setCreateTime(new Date());
                //默认密码123456
                user.setPassword(ENCODER.encode("123456"));
                userMapper.insertSelective(user);
                //默认菜单
                List<Integer> listMenu = menuMapper.getStaticMenu();
                for (Integer menu:listMenu) {
                    menuMapper.insertUserMenu(user.getId(),menu);
                }
            }else{
                buffer.append(user.getUserName()+";");
            }
        }
        if(buffer.length()>0){
            result.setData(buffer.toString()+"系统已存在相同用户名用户");
        }
        return result;
    }

    @Override
    public Result upPassword(String oldPassword,String newPassword, String userName) {
        Result result = new Result();
        TabUser tabUser = userMapper.getByUserName(userName);
        if(null != tabUser && StrUtil.isNotBlank(newPassword) && StrUtil.isNotBlank(oldPassword)){
            if (!ENCODER.matches(oldPassword, tabUser.getPassword())) {
                return result.failure(-1,"原始密码输入错误");
            }
            if (ENCODER.matches(newPassword, tabUser.getPassword())) {
                result.failure(-1,"新旧密码相同");
            }else{
                tabUser.setPassword(ENCODER.encode(newPassword));
                userMapper.upSelective(tabUser);
                result.success("修改成功");
            }
        }else{
            result.failure(-1,"信息不能为空");
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(ENCODER.encode("123456"));

    }
}
